import {
  HostBinding,
  Component,
  OnInit,
  ViewChild,
  Input,
  Renderer2,
  forwardRef,
  Injector,
  Inject,
  DoCheck,
  OnDestroy,
  ChangeDetectorRef
} from "@angular/core";
import {
  Observable,
  Subject,
  ReplaySubject,
  from,
  of,
  range,
  BehaviorSubject,
  Subscription
} from "rxjs";
import { map, catchError, filter } from "rxjs/operators";
import { Router } from "@angular/router";
import {
  AsyncValidator,
  NG_ASYNC_VALIDATORS,
  ValidationErrors,
  AbstractControl,
  FormBuilder,
  FormGroup,
  Validators,
  ControlValueAccessor,
  NG_VALUE_ACCESSOR,
  FormControl
} from "@angular/forms";
import { Store, select } from "@ngrx/store";
import { Actions } from "@ngrx/effects";
import * as fromUser from "@/user/store/reducers/index";
import * as fromRoot from "@/reducers/index";
import { UserActions } from "@/user/store/actions";
import { ILoginRequest } from "@/user/store/models/user";

import { PLATFORM_ID, APP_ID } from "@angular/core";
import { isPlatformServer } from "@angular/common";
import { LocaleService, TranslationService, Language } from "angular-l10n";
import { EhAnimateService } from "@/share/services/eh-animate.service";

export interface IAddBugRequest {
  email: string;
  url: string;
  title: string;
  review: string;
  sys: string;
  img: Array<string>;
  browser: string;
}

@Component({
  selector: "app-bug",
  templateUrl: "./bug.component.html",
  styleUrls: ["./bug.component.scss"],
  animations: [EhAnimateService.fadeInOut()]
})
export class BugComponent implements OnInit, DoCheck, OnDestroy {
  @Language() lang: string;

  validateForm: FormGroup;

  hide = true;

  type = {
    email: "1",
    phone: "2"
  };

  timer;

  @ViewChild("email")
  email;

  @ViewChild("sliderCodeRef")
  sliderCodeRef;

  isServer: boolean;

  private valueChangesSub: Subscription;

  user: any = {
    username: ""
  };

  user$ = this.store.pipe(
    select(fromRoot.user),
    filter(user => !!user)
  );

  sub$ = {
    userSub$: null
  };

  sysLists = [
    {
      label: "Windows"
    },
    {
      label: "macOS"
    },
    {
      label: "Linux"
    },
    {
      label: "iOS"
    },
    {
      label: "Android"
    }
  ];

  browserLists = [
    {
      label: "Chrome"
    },
    {
      label: "Firefox"
    },
    {
      label: "Safari"
    },
    {
      label: "IE"
    }
  ];

  req: IAddBugRequest = {
    email: "",
    url: "",
    title: "",
    review: "",
    sys: "",
    img: [],
    browser: ""
  };

  @ViewChild("file")
  file;

  isGotBug = false;

  constructor(
    updates$: Actions,
    @Inject(PLATFORM_ID) private platformId: Object,
    private fb: FormBuilder,
    private renderer: Renderer2,
    @Inject("BugService") private bugService,
    @Inject("AccountService") private accountService,
    @Inject("StoreService") private storeService,
    @Inject("RegService") private regService,
    @Inject("UtilsService") private utilsService,
    @Inject("UserService") private userService,
    @Inject("MsgService") private msgService,
    @Inject("HasUsernameValidatorService") private hasUsernameValidatorService,
    @Inject("CookieService") private cookieService,
    @Inject("DialogService") private dialogService,
    private router: Router,
    private store: Store<fromUser.State | fromRoot.State>,
    private changeDetectorRef: ChangeDetectorRef
  ) {
    this.isServer = isPlatformServer(this.platformId);
  }

  ngOnInit(): void {
    // email, url, title, review, sys, img, browser
    this.validateForm = this.fb.group({
      email: [null, [Validators.required]],
      url: [null, [Validators.required]],
      title: [null, [Validators.required]],
      review: [null, [Validators.required]],
      img: [null, [Validators.required]],
      sys: [null, [Validators.required]],
      browser: [null, [Validators.required]]
    });

    if (
      Object.prototype.toString.call(this.cookieService.get("isGotBug")) ===
      "[object Undefined]"
    ) {
      this.cookieService.putObject("isGotBug", (this.isGotBug = false));
    } else {
      this.isGotBug = this.cookieService.get("isGotBug") === "true";
    }

    const timer = setTimeout(() => {
      if (this.cookieService.get("isGotBug") === "true") {
        return;
      }
      clearTimeout(timer);
    }, 0);
    this.addListen();
  }

  debounce(fn, time = 1000) {
    if (this.timer) {
      clearTimeout(this.timer);
    }
    this.timer = setTimeout(() => {
      fn();
      clearTimeout(this.timer);
    }, time);
  }

  toggleSample() {
    this.cookieService.putObject(
      "isGotBug",
      (this.isGotBug = !(this.cookieService.get("isGotBug") === "true"))
    );
  }

  ngDoCheck() {}

  addListen() {
    this.valueChangesSub = this.validateForm.valueChanges.subscribe(e => {
      this.req = e;
    });
    this.sub$.userSub$ = this.user$.subscribe(e => {
      this.user.username = e.username;
      this.validateForm.controls.email.setValue(e.username);
    });
  }

  async onSubmit() {
    // 验证码如果验证失败可以重置
    // this.store.dispatch(new UserActions.Login({ req: this.req, cpt: this }));
    this.bugService.addBug({ ...this.req }).subscribe(e => {
      if (e.code === 200) {
        this.msgService.success("success");
        this.validateForm.reset();
        this.file.clear();
      }
    });
  }

  onChangeFile(e) {
    this.validateForm.controls.img.setValue(
      e.slice().map(d => {
        return d.id;
      })
    );
  }

  ngOnDestroy() {}
}
